1
Local Object Lifetimes: Automatic vs. Static
AI037 Lesson 10
00:00

In the theater of C++, every object has a lifespan—the object lifetime. This defines the duration an object occupies space in memory. Within a function body, the default behavior for local variables is to be automatic, but we can command them to be static to change their destiny.

1. Automatic Objects

By default, local variables are automatic objects. They are born (initialized) when the function execution hits their definition and die (are reclaimed) when the block completes. They reside on the stack, making them fresh for every call.

2. Local Static Objects

When you use the static keyword, you create a local static object. These are initialized only once—before the first time control passes through their definition—and remain alive until the program terminates. This allows a function to "remember" state without polluting the global scope.

Stack (Automatic) [ temp_val ] Destroyed at block end Data Segment (Static) [ persistent_val ] Lives until program exit

3. The Recursion Trap

In a recursive function, every recursion loop creates a distinct instance of its automatic objects. If the recursion is deep, this consumes significant stack space. Conversely, a static object is shared across every level of that recursion.

main.py
TERMINAL bash — 80x24
> Ready. Click "Run" to execute.
>